package com.SkyAI.test.socket;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
	public Socket ser = null;
	private DataInputStream is = null;
	private OutputStream os = null;
	private int _port = 0;
	ServerSocket server = null;

	public SocketServer(int port) {
		this._port = port;
	}

	public int server() {
		try {
			server = new ServerSocket(_port);// 在端口719建立一个服务器套接字对象
			System.out.println("Server prot is ready");
			// while (true) {
			System.out.println("Socket serve waiting");
			ser = server.accept();// 客户端向我们建立的
									// 服务器套接字发送连接请求,则向下执行
			is = new DataInputStream(new BufferedInputStream(
					ser.getInputStream()));
			os = ser.getOutputStream();
			System.out.println("Socket server connection the client");
			// }
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				if (server != null)
					server.close();// 关闭服务器套接字。 为什么要用finally关键字来做这个事呢？HOHO
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
		return 1;

	}

	public int serAccept(byte[] bAccept) {
		try {
			return is.read(bAccept);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}

	public int serPut(byte[] bWrite, int iSize) {
		try {
			os.write(bWrite, 0, iSize);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
}
